#
# Copyright 2009 Red Hat, Inc. and/or its affiliates.
#
# Licensed to you under the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.  See the files README and
# LICENSE_GPL_v2 which accompany this distribution.
#


"""
Various LVM aux procedures
"""

import os
import logging
import misc

import multipath
import vg
from config import config

log = logging.getLogger("irs")

LVMCONF_TEMPLATE = """
devices {
preferred_names = ["^/dev/mapper/"]
write_cache_state=0
%s
}

backup {
 retain_min = 50
 retain_days = 0
}
"""

_conf = LVMCONF_TEMPLATE % 'filter = [ "r|.*|" ]'
EXTRA_LVMCONF = _conf.replace("\n", " ")

VAR_RUN_VDSM = "@VDSMRUNDIR@"
VDSM_LVM_SYSTEM_DIR = os.path.join(VAR_RUN_VDSM, "lvm")
VDSM_LVM_CONF = os.path.join(VDSM_LVM_SYSTEM_DIR, "lvm.conf")

def buildFilter(autodevList):
    try:
        userDevList = config.get("irs", "lvm_dev_whitelist").split(",")
    except:
        userDevList = []
    devList = userDevList + autodevList
    devList.sort()
    filt = '|'.join([dev.strip() for dev in devList if len(dev.strip()) > 0])
    if len(filt) > 0:
        filt = '"a%' + filt + '%", '
    filt = 'filter = [ ' + filt + '"r%.*%" ]'
    return filt


def setupLVM():
    updateLvmConf()
    try:
        lvmenvfname = os.path.join(VAR_RUN_VDSM, "lvm.env")
        lvmenv = file(lvmenvfname, "w")
        lvmenv.write("export LVM_SYSTEM_DIR=%s\n" % VDSM_LVM_SYSTEM_DIR)
        lvmenv.close()
    except Exception, e:
        log.warning("Cannot create %s file", lvmenvfname)
        misc.logException(e)


def updateLvmConf():
    global EXTRA_LVMCONF

    mpdevs = [os.path.join("/dev/mapper", i) for i in multipath.getMPDevNames()]

    conf = LVMCONF_TEMPLATE % buildFilter(mpdevs)
    EXTRA_LVMCONF = conf.replace("\n", " ")

    # Make a convenience copy for the debugging purposes
    try:
        if not os.path.isdir(VDSM_LVM_SYSTEM_DIR):
            os.mkdir(VDSM_LVM_SYSTEM_DIR)
        lvmconf = file(VDSM_LVM_CONF, "w")
        lvmconf.write(EXTRA_LVMCONF)
        lvmconf.close()
    except Exception, e:
        # We are not interested in exceptions here, note it and
        log.warning("Cannot create %s file", VDSM_LVM_CONF)
        misc.logException(e)

    # vgscan is called to refresh the lvm device cache according to new filter
    vg.rescan()


def addExtraCfg(cmd, devList=None):
    if devList is not None:
        devList = list(set(devList))
        devList.sort()
        conf = LVMCONF_TEMPLATE % buildFilter(devList)
        conf = conf.replace("\n", " ")
        newcmd = [cmd[0], "--config", conf]
    else:
        newcmd = [cmd[0], "--config", EXTRA_LVMCONF]

    if len(cmd) > 1:
        newcmd += cmd[1:]

    return newcmd
